class StateMachine:
    def __init__(self):
        self.states = {}
        self.current_state = None

    def add_state(self, state_name, handler):
        self.states[state_name] = handler

    def set_initial_state(self, state_name):
        self.current_state = state_name

    def transition_to(self, new_state_name):
        if self.current_state == new_state_name:
            return  # 如果当前状态已经是新状态，则直接返回，不进行状态切换
        if self.current_state in self.states:
            current_state_handler = self.states[self.current_state]
            current_state_handler.exit()  # 离开当前状态时执行一次

        if new_state_name in self.states:
            new_state_handler = self.states[new_state_name]
            new_state_handler.enter()  # 进入新状态时执行一次
            self.current_state = new_state_name

    def run_current_state(self):
        if self.current_state in self.states:
            current_state_handler = self.states[self.current_state]
            current_state_handler.run()  # 当前状态一直运行


# 示例状态处理器
class StateHandler:
    def enter(self):
        print(f"Entering state: {type(self).__name__}")

    def run(self):
        print(f"Running state: {type(self).__name__}")

    def exit(self):
        print(f"Exiting state: {type(self).__name__}")


# 使用示例
if __name__ == "__main__":
    sm = StateMachine()

    # 添加不同的状态处理器
    sm.add_state("state1", StateHandler())
    sm.add_state("state2", StateHandler())
    sm.add_state("state3", StateHandler())

    # 设置初始状态
    sm.set_initial_state("state1")

    # 模拟状态切换和运行
    sm.run_current_state()  # 运行state1
    sm.transition_to("state2")  # 切换到state2
    sm.run_current_state()  # 运行state2
    sm.transition_to("state3")  # 切换到state3
    sm.run_current_state()  # 运行state3
    sm.transition_to("state1")  # 再次切换到state1
    sm.run_current_state()  # 运行state1
